<?php
class card_service{
	
	public $_messageCode;
	public $_responseMessage;

	public function alpha_encode($in, $to_num = false, $pad_up = false, $passKey = null){
			
		$index = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
		if ($passKey !== null) {
			// Although this function's purpose is to just make the
			// ID short - and not so much secure,
			// with this patch by Simon Franz (http://blog.snaky.org/)
			// you can optionally supply a password to make it harder
			// to calculate the corresponding numeric ID
	
			for ($n = 0; $n<strlen($index); $n++) {
				$i[] = substr( $index,$n ,1);
			}
	
			$passhash = hash('sha256',$passKey);
			$passhash = (strlen($passhash) < strlen($index))
			? hash('sha512',$passKey)
			: $passhash;
	
			for ($n=0; $n < strlen($index); $n++) {
				$p[] =  substr($passhash, $n ,1);
			}
	
			array_multisort($p,  SORT_DESC, $i);
			$index = implode($i);
		}
	
		$base  = strlen($index);
	
		if ($to_num) {
			// Digital number  <<--  alphabet letter code
			$in  = strrev($in);
			$out = 0;
			$len = strlen($in) - 1;
			for ($t = 0; $t <= $len; $t++) {
				$bcpow = bcpow($base, $len - $t);
				$out   = $out + strpos($index, substr($in, $t, 1)) * $bcpow;
			}
	
			if (is_numeric($pad_up)) {
				$pad_up--;
				if ($pad_up > 0) {
					$out -= pow($base, $pad_up);
				}
			}
			$out = sprintf('%F', $out);
			$out = substr($out, 0, strpos($out, '.'));
		} else {
			// Digital number  -->>  alphabet letter code
			if (is_numeric($pad_up)) {
				$pad_up--;
				if ($pad_up > 0) {
					$in += pow($base, $pad_up);
				}
			}
	
			$out = "";
			for ($t = floor(log($in, $base)); $t >= 0; $t--) {
				$bcp = bcpow($base, $t);
				$a   = floor($in / $bcp) % $base;
				$out = $out . substr($index, $a, 1);
				$in  = $in - ($a * $bcp);
			}
			$out = strrev($out); // reverse
		}
	
		return $out;
	}

	public function check_charging_status($arrParams, $cardProvider, $time){
		return '99|He thong dang quet';
		$ch = curl_init();
		$url = 'http://202.160.125.55/voucher/useCard.html';
		// Header
		$header=array(
				'User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12',
				'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
				'Accept-Language: en-us,en;q=0.5',
				'Accept-Encoding: gzip,deflate',
				'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
				'Keep-Alive: 115',
				'Connection: keep-alive',
		);
		
		// Post data
		$data = array(
					'issuer'		=>	$cardProvider['type'],
					'cardSerial'	=>	$arrParams['txt_card_serial'],
					'cardCode'		=>	$arrParams['txt_card_pin'],
					'transRef'		=>	$arrParams['transRef'],
					'partnerCode'	=>	'homedirect',
					'password'		=>	'123456',
					'secretKey'		=>	'homedirect_sk',
				);
		$data['signature'] = md5($data['issuer'] .
				$data['cardCode'] .
				$data['transRef'] .
				$data['partnerCode'] .
				$data['password'] .
				$data['secretKey']);
		
		curl_setopt($ch,CURLOPT_URL,$url);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
		curl_setopt($ch,CURLOPT_HTTPHEADER,$header);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		curl_setopt($ch, CURLOPT_TIMEOUT, 30); //timeout in seconds
		$result=curl_exec($ch);
		curl_close($ch);
		return $result;
	}
	
	public function processSuccessCharging($arrParams, $resultResponseArr, $time){
		$configGame = unserialize(CONFIG_GAME);
		$_SESSION['user']['fraud_card_submit'] = '';
		$_SESSION['user']['fraud_card_last_submit'] = '';
	
		//$modelCardCharging = new Default_Model_CardCharging();
	
		$arrParams['date'] = date('Y-m-d H:i:s', $time);
		$arrParams['user_id'] = $_SESSION['user']['id'];
		$arrParams['card_value'] = $resultResponseArr[2];
		$arrParams['cash_value'] = ($resultResponseArr[2] * (float) $configGame['cash_rate']);
	
		$model = new Model();
		$data = array(
					'user_id'	=> $_SESSION['user']['id'],
					'card_provider_id'	=> $arrParams['txt_card_provider'],
					'card_value'		=> $arrParams['card_value'],
					'cash_value'		=> $arrParams['cash_value'],
					'pin_number'		=> $arrParams['txt_card_pin'],
					'serial_number'		=> $arrParams['txt_card_serial'],
					'trans_ref'			=> $arrParams['transRef'],
					'date'				=> date('Y-m-d H:i:s', $time)
				);

		if(!$model->insert('card_charging', $data)) return false;
		
		$where = "card_pin = '" . $arrParams['txt_card_pin'] . "'";
		$model->delete('pending_card_charging');
		
		$model->where = "id = '" . $_SESSION['user']['id'] . "'";
		$model->getdata('user');
		$user = $model->fetchOne();

		if($user){
			$newCash = (int) $user['scash'] + $arrParams['cash_value'];
			$model->where = "id = '" . $_SESSION['user']['id'] . "'";
			$model->update('user', array('scash' => $newCash));
		}
		return true;
	
	}
	
	public function processFailureCharging($arrParams, $resultResponseArr, $time){
		$model = new Model();
		$this->_messageCode = $resultResponseArr[0];
		if($resultResponseArr[0] == '08' || $resultResponseArr[0] == '13' || $resultResponseArr[0] == '99'){
	
		}else{
			$_SESSION['user']['fraud_card_submit'] += 1;
			$_SESSION['user']['fraud_card_last_submit'] = $time;
		}
			
		//Save all the fail transactions to database
		$data = array(
				'uid'				=> $_SESSION['user']['id'],
				'trans_ref'			=> $arrParams['transRef'],
				'card_provider_id'	=> $arrParams['txt_card_provider'],
				'card_serial'		=> $arrParams['txt_card_serial'],
				'card_pin'			=> $arrParams['txt_card_pin'],
				'failure_code'		=> $resultResponseArr[0],
				'charging_date'		=> date('Y-m-d H:i:s', $time),
				'status'			=> 1
		);
			
		if(!$model->insert('pending_card_charging', $data)){
			require 'function/logging.php';
			$log = new Logging();
			$log->lfile(BASE_PATH . '/log/pending.txt');
			$log->lwrite('Could not insert pending card charging into database: ');
			foreach($data as $key => $value){
				$log->lwrite($key . ' : ' . $value);
			}
			$log->lwrite('--------------------------------------------');
		}
	
	}
	
	public function getFailMessageCharging(){
		if(!$this->_messageCode){
			$this->_responseMessage = 'Undefined message';
			return;
		}
			
		switch($this->_messageCode){
			case '00':
				$this->_responseMessage = 'Mã số nạp tiền không tồn tại hoặc đã được sử dụng';
				break;
					
			case '03':
				$this->_responseMessage = 'Thẻ đã được sử dụng.';
				break;
					
			case '04':
				$this->_responseMessage = 'Thẻ đã bị khóa.';
				break;
					
			case '05':
				$this->_responseMessage = 'Thẻ đã hết hạn sử dụng.';
				break;
					
			case '05':
				$this->_responseMessage = 'Thẻ chưa được kích hoạt.';
				break;
					
			case '07':
				$this->_responseMessage = 'Thực hiện sai quá số lần cho phép.';
				break;
					
			case '08':
			case '13':
				$this->_responseMessage = 'Việc nạp thẻ chưa được xử lý kịp. Vui lòng liên hệ với chúng tôi để được hỗ trợ.';
				break;
					
			case '09':
				$this->_responseMessage = 'Sai định dạng thông tin truyền vào.';
				break;
					
			case '10':
			case '11':
			case '14':
			case '15':
			case '16':
			case '21':
			case '25':
			case '26':
			case '40':
			case '41':
			case '51':
			case '52':
			case '99':
				$this->_responseMessage = 'Lỗi hệ thống. Xin vui lòng thử lại.';
				break;
	
			case '20':
				$this->_responseMessage = 'Sai độ dài mã số nạp tiền.';
				break;
	
			case '23':
				$this->_responseMessage = 'Serial thẻ không hợp lệ (áp dung cho thẻ Viettel).';
				break;
					
			case '24':
				$this->_responseMessage = 'Mã số nạp tiền và serial không khớp (áp dung cho thẻ VT).';
				break;
					
			case '28':
				$this->_responseMessage = 'Mã số nạp tiền không đúng định dạng (chỉ bao gồm ký tự số).';
				break;
		}
			
		return $this->_responseMessage;
	}
	
}


